package com.sdy.resdir.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.approval.biz.model.TpApproveFlow;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.service.FileService;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.service.*;
import com.sdy.resdir.biz.vo.CatalogVO;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.UserDTO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 申请资源详细（子） 前端控制器
 * </p>
 *
 * @author hyh
 * @since 2019-10-21
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@Api(tags = "资源申请单-订单控制器")
@RequestMapping("/rdResourceApplicationDetail")
public class RdResourceApplicationDetailController extends BaseController {
    @Autowired
    private RdResourceApplicationDetailService resAppDetailService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private RdOrderAppService rdOrderAppService;
    @Autowired
    private RdResForOnlineService rdResForOnlineService;
    @Autowired
    private RdImplementationOrderService rdImplementationOrderService;
    @Autowired
    private RdResDetailsApiService rdResDetailsApiService;
    @Autowired
    private FsApi fsApi;
    @Autowired
    private FileService fileService;
    @Autowired
    private RdDbDictService rdDbDictService;
    @Autowired
    private RdResourceDirDataService rdResourceDirDataService;
    @Autowired
    private RdResDataItemService rdResDataItemService;
    @Autowired
    private RdDbAppService dbAppService;
    @Value("${res.app.code}")
    private String appCode;


    public static String randomNum() {
        // 获取随机申请订单
        long dateEx = System.currentTimeMillis();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeEx = dateFormat.format(dateEx);
        int aEx = (int) (Math.random() * 900 + 100);
        String randomThree = Integer.toString(aEx);
        String randomNum = timeEx + randomThree;
        return randomNum;
    }

    @ApiOperation(value = "点击应用后加入购物车(加入申请栏)", httpMethod = "POST")
    @PostMapping("/createNewApply")
    public Response createNewApply(HttpServletRequest request,
                                   @RequestBody @ApiParam(name = "resId & resName & resType & resSituation",
                                           value = "传入resId 和 resName 和 resType 和 resSituation") Map<String, Object> map) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        UserDTO user = userQueryApi.getUser(userInfo.getUserId());
        Assert.isNull(userInfo, "用户未登录");
        Integer ownDeptId = user.getOwnDeptId();
        // 判断是否重复加入购物车
        LambdaQueryWrapper<RdResourceApplicationDetail> selectDetail = new LambdaQueryWrapper<>();
        selectDetail.eq(map.get("resId") != null, RdResourceApplicationDetail::getResId, map.get("resId"))
                .ne(RdResourceApplicationDetail::getState, 5)
                .eq(ownDeptId != null, RdResourceApplicationDetail::getDeptId, ownDeptId);
        RdResourceApplicationDetail oneDetail = resAppDetailService.getOne(selectDetail);
        if (oneDetail != null) {
            return Response.error("您所属部门已申请该资源或您已将该资源加入购物车!");
        }
        Integer resType = (Integer) map.get("resType");
        Assert.isTrue(resType == 3, "对不起！交换类资源不支持加入到购物车！");
        boolean save = resAppDetailService.save(new RdResourceApplicationDetail()
                .setApplyNumFather(randomNum() + "")
                .setApplyTime(new Date())
                .setResId((Integer) map.get("resId"))
                .setResName((String) map.get("resName"))
                .setType(2)
                .setDeptId(user.getOwnDeptId())
                .setApplyUserId(userInfo.getUserId())
                .setState(1)
                .setApplyDeptName(user.getOwnDeptName())
                .setResType(resType)
                .setResSituation((Integer) map.get("resSituation"))
                .setApplyNumChild(randomNum() + "-" + map.get("resId")));
        return save ? Response.success("加入申请栏成功") : Response.error("加入申请栏失败");
    }

    @ApiOperation(value = "购物车数据", response = RdResourceApplicationDetail.class)
    @GetMapping("/selectApplyCars")
    public Response selectApplyCars(HttpServletRequest request, Page page) {

        LambdaQueryWrapper<RdResourceApplicationDetail> lqwWrapper = new LambdaQueryWrapper<>();
        Integer userId = ssoService.getUserId(request);
        // 资源申请人id
        lqwWrapper.eq(null != userId, RdResourceApplicationDetail::getApplyUserId, userId);
        // 资源类型
        lqwWrapper.eq(RdResourceApplicationDetail::getType, 2);
        // 不带有版本的
        lqwWrapper.isNull(RdResourceApplicationDetail::getVersionNum);
        // 订单状态为未提交时
        lqwWrapper.eq(RdResourceApplicationDetail::getState, 1);
        // 倒序输出
        lqwWrapper.orderByDesc();
        List<RdResourceApplicationDetail> listDetail = resAppDetailService.list(lqwWrapper);

        List<Integer> collectResId = listDetail.stream().map(RdResourceApplicationDetail::getResId).collect(Collectors.toList());
        if (collectResId.isEmpty()) {
            return Response.success(new Page().setSize(page.getSize()).setCurrent(page.getCurrent()));
        }
        // 查询出dir的部门名称和接口状态
        LambdaQueryWrapper<RdResourceDir> selectDir = new LambdaQueryWrapper<>();
        selectDir.in(RdResourceDir::getId, collectResId);
        List<RdResourceDir> listDir = rdResourceDirService.list(selectDir);
        List<String> collectDeptName = listDir.stream().map(RdResourceDir::getResSourceDept).collect(Collectors.toList());
        List<Integer> collectResState = listDir.stream().map(RdResourceDir::getResState).collect(Collectors.toList());
        for (int i = 0; i < listDetail.size(); i++) {
            listDetail.get(i).setResSourceDept(collectDeptName.get(i));
            listDetail.get(i).setResState(collectResState.get(i));
        }
        Page<RdResourceApplicationDetail> pageData = new Page<RdResourceApplicationDetail>().setRecords(listDetail).setCurrent(page.getCurrent()).setSize(page.getSize());
        return Response.success(pageData);
    }

    @ApiOperation("删除购物车选项")
    @PostMapping("/delById")
    public Response delById(@RequestBody @ApiParam(name = "id", value = "主键id") Map<String, Object> map) throws BizException {
        String idList = (String) map.get("idList");
        Assert.isTrue(idList.isEmpty(), "请选择移除的购物车数据");
        String decode = URLDecoder.decode(idList);
        String[] id = decode.split(",");
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < id.length; i++) {
            int idInt = Integer.valueOf(id[i]);
            list.add(idInt);
        }
        return Response.success(resAppDetailService.removeByIds(list));
    }

    @ApiOperation("已上线资源申请单提交(单条独立申请)")
    @PostMapping("/saveApply")
    public Response<String> saveApply(HttpServletRequest request, @RequestBody
    @ApiParam(name = "RdResourceApplicationDetail", value = "实体类，把自建系统数据放到orderApps里!如果是交换类，把数据源字段信息放到" +
            "dbApps，这是一个list")
            RdResourceApplicationDetail rdResourceApplicationDetail) throws BizException {
        // 准备需要的数据
        // 获取随机申请订单
        Integer userId = ssoService.getUserId(request);
        String randomNum = randomNum();
        Integer intResId = rdResourceApplicationDetail.getIdList().get(0);
        Boolean aBoolean = resAppDetailService.saveApply(rdResourceApplicationDetail, userId, randomNum);
        Assert.notTrue(aBoolean, "申请失败！");
        return Response.success(randomNum + "-" + intResId);
    }

    @ApiOperation("查询购物车提交的资源申请")
    @PostMapping("/selectApplyResIdList")
    public Response<List<Integer>> selectApplyResIdList(@RequestBody Map<String, Object> map) {
        List<Integer> idList = (List<Integer>) map.get("idList");
        LambdaQueryWrapper<RdResourceApplicationDetail> selectResWrapper = new LambdaQueryWrapper<>();
        selectResWrapper.in(RdResourceApplicationDetail::getId, idList)
                .isNull(RdResourceApplicationDetail::getVersionNum);
        List<RdResourceApplicationDetail> list = resAppDetailService.list(selectResWrapper);
        List<Integer> resIdList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            resIdList.add(list.get(i).getResId());
        }
        return Response.success(resIdList);
    }

    @ApiOperation(value = "详细信息资源列表(立即申请)", response = RdResourceApplicationDetail.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "idList", value = "购物车选中的资源订单id")
    })
    @GetMapping("/selectApplyResBatch")
    public Response selectApplyResBatch(String idList, HttpServletRequest request) throws BizException {
        Assert.isTrue(!StringUtil.isNotBlank(idList) && !StringUtil.isNotEmpty(idList), "必须选中资源");
        String decode = URLDecoder.decode(idList);
        String[] detailId = decode.split(",");
        List<Integer> detailIdList = new ArrayList<>();
        for (int i = 0; i < detailId.length; i++) {
            if (StringUtil.isNotBlank(detailId[i]) && StringUtil.isNotEmpty(detailId[i])) {
                int detailIdInt = Integer.valueOf(detailId[i]);
                detailIdList.add(detailIdInt);
            }
        }

        // 排除资源的重复申请
        LambdaQueryWrapper<RdResourceApplicationDetail> selectDetail = new LambdaQueryWrapper<>();
        selectDetail.in(RdResourceApplicationDetail::getId, detailIdList)
                .eq(RdResourceApplicationDetail::getApplyUserId, ssoService.getUserId(request))
                .in(RdResourceApplicationDetail::getState, 2, 3, 6);
        List<RdResourceApplicationDetail> listDetail = resAppDetailService.list(selectDetail);
        if (listDetail.size() > 0) {
            return Response.error("存在重复申请的资源");
        }

        // 查询提交的资源数据
        LambdaQueryWrapper<RdResourceApplicationDetail> selectDetailResId = new LambdaQueryWrapper<>();
        selectDetailResId.in(RdResourceApplicationDetail::getId, detailIdList);
        List<RdResourceApplicationDetail> listDetailForDirId = resAppDetailService.list(selectDetailResId);
        List<Integer> collectResId = listDetailForDirId.stream().map(RdResourceApplicationDetail::getResId).collect(Collectors.toList());
        if (collectResId.isEmpty()) {
            return Response.success(new ArrayList<>());
        }
        // 查询资源信息
        LambdaQueryWrapper<RdResourceDir> selectDir = new LambdaQueryWrapper<>();
        selectDir.in(RdResourceDir::getId, collectResId);
        List<RdResourceDir> listDir = rdResourceDirService.list(selectDir);
        return Response.success(listDir);
    }

    @ApiOperation(value = "资源信息", response = RdResourceApplicationDetail.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "idList", value = "选中的资源id")
    })
    @GetMapping("/selectApplyResOne")
    public Response selectApplyResOne(String idList, HttpServletRequest request) throws BizException {
        String decode = URLDecoder.decode(idList);
        String[] resId = decode.split(",");
        List<Integer> resIdList = new ArrayList<>();
        for (int i = 0; i < resId.length; i++) {
            if (StringUtil.isNotBlank(resId[i]) && StringUtil.isNotEmpty(resId[i])) {
                int detailIdInt = Integer.valueOf(resId[i]);
                resIdList.add(detailIdInt);
            }
        }
        // 排除资源的重复申请
        LambdaQueryWrapper<RdResourceApplicationDetail> selectDetail = new LambdaQueryWrapper<>();
        selectDetail.in(RdResourceApplicationDetail::getResId, resIdList)
                .eq(RdResourceApplicationDetail::getApplyUserId, ssoService.getUserId(request))
                .in(RdResourceApplicationDetail::getState, 2, 3, 4, 6, 7);
        List<RdResourceApplicationDetail> listDetail = resAppDetailService.list(selectDetail);
        if (listDetail.size() > 0) {
            return Response.error("存在重复申请的资源");
        }

        // 判断该资源是否有编目信息，没有则不能申请
        List<RdResourceDir> rdResourceDirs = rdResourceDirService.list(new LambdaQueryWrapper<RdResourceDir>().in(RdResourceDir::getId, resIdList));
        UserInfo userInfo = ssoService.getUserInfo(request);
        UserDTO user = userQueryApi.getUser(userInfo.getUserId());
        Integer deptId = user.getOwnDeptId();
        String deptName = user.getOwnDeptName();
        List<RdDbDict> rdDbDictList = rdDbDictService.list(new LambdaQueryWrapper<RdDbDict>().eq(RdDbDict::getDeptId, deptId));
        // 上传路径
        String fsUploadAddr = fileService.getFsUploadAddr();
        // 循环查看资源是否有编目
        for (RdResourceDir rdResourceDir : rdResourceDirs) {
            CatalogVO catalogVO = new CatalogVO();
            // 接口类资源
            if (rdResourceDir.getResType() == 1) {
                RdResDetailsApi rdResDetailsApi = rdResDetailsApiService.getOne(new LambdaQueryWrapper<RdResDetailsApi>()
                        .in(RdResDetailsApi::getResDirId, resIdList));
                Assert.isNull(rdResDetailsApi, "资源:" + rdResourceDir.getResName() + "无编目信息");
                // 存放资源提供部门id
                catalogVO.setDeptId(rdResourceDir.getResSourceDeptId());
                // 存放资源提供部门名称
                catalogVO.setDeptName(rdResourceDir.getResSourceDept());
                // 存放接口类资源编目信息
                catalogVO.setRdResDetailsApi(rdResDetailsApi);
                // 存放当前部门拥有的数据库及当前部门id，名称
                rdResourceDir.setCatalogVO(catalogVO)
                        .setRdDbDictList(rdDbDictList)
                        .setUploadUrl(fsUploadAddr);
                // 交换类资源
            } else if (rdResourceDir.getResType() == 3) {
                List<RdResDataItem> rdResDataItems = rdResDataItemService.list(Wrappers.<RdResDataItem>lambdaQuery()
                        .eq(RdResDataItem::getOwnResId, rdResourceDir.getId()));
                Assert.isTrue(rdResDataItems.isEmpty(), "资源" + rdResourceDir.getResName() + "无编目信息");
                // 存放资源提供部门id
                catalogVO.setDeptId(rdResourceDir.getResSourceDeptId());
                // 存放资源提供部门名称
                catalogVO.setDeptName(rdResourceDir.getResSourceDept());
                // 存放交换类资源编目信息
                catalogVO.setRdResDataItemList(rdResDataItems);
                // 存放资源信息，数据库列表，当前部门id及名称
                rdResourceDir.setCatalogVO(catalogVO)
                        .setRdDbDictList(rdDbDictList)
                        .setUploadUrl(fsUploadAddr);
            }
        }
        return Response.success(rdResourceDirs);
    }

    @ApiOperation("申请单提交（加入购物车申请）")
    @PostMapping("/updateApplyBatch")
    public Response updateApplyBatch(HttpServletRequest request,
                                     @RequestBody @ApiParam(name = "RdResourceApplicationDetail", value = "实体类，传入选中的购物车数据，" +
                                             "把选中的id以List形式放到idList里面，把自建系统数据放到orderApps里,contactName放联系人,contactTel联系方式" +
                                             "remark申请说明,enclosure附件信息")
                                             RdResourceApplicationDetail raDetail) throws BizException {
        // 准备需要的数据
        List<Integer> idList = raDetail.getIdList();
        List<RdOrderApp> orderApps = raDetail.getOrderApps();
        Integer userId = ssoService.getUserId(request);
        Date date = new Date();

        LambdaQueryWrapper<RdResourceApplicationDetail> selectWrapper = new LambdaQueryWrapper<>();
        selectWrapper.in(RdResourceApplicationDetail::getId, idList)
                .isNull(RdResourceApplicationDetail::getVersionNum);
        List<RdResourceApplicationDetail> listDetail = resAppDetailService.list(selectWrapper);
        // 获取订单号信息
        List<String> applyNums = listDetail.stream().map(RdResourceApplicationDetail::getApplyNumChild).collect(Collectors.toList());

        // 拒绝重复提交申请
        List<Integer> collectState = listDetail.stream().map(RdResourceApplicationDetail::getState).collect(Collectors.toList());
        for (int i = 0; i < collectState.size(); i++) {
            if (collectState.get(i) == 3 || collectState.get(i) == 2 || collectState.get(i) == 4 || collectState.get(i) == 6) {
                return Response.error("此次提交中含有您已经提交的资源申请");
            }
        }
        // 对应订单的的对应资源类型
        List<Integer> resTypes = listDetail.stream().map(RdResourceApplicationDetail::getResType).collect(Collectors.toList());
        // 如果是接口数据，则有自建系统
        try {
            for (int i = 0; i < idList.size(); i++) {
                if (resTypes.get(i).equals(1) || resTypes.get(i).equals(3)) {
                    RdResourceApplicationDetail order = new RdResourceApplicationDetail()
                            .setId(idList.get(i))
                            .setState(3)
                            .setApplyUserId(userId)
                            .setApplyDeptName(userQueryApi.getUser(ssoService.getUserId(request)).getOwnDeptName())
                            .setApplyTime(date)
                            .setModifyTime(date)
                            .setApplyDeptName(raDetail.getApplyDeptName())
                            .setContactName(raDetail.getContactName())
                            .setContactTel(raDetail.getContactTel())
                            .setRemark(raDetail.getRemark())
                            .setEnclosure(raDetail.getEnclosure());
                    boolean update = resAppDetailService.updateById(order);
                    Assert.notTrue(update, "购物车订单提交时出现数据错误,第" + i + "条");
                    // 批量新增自建系统
                    boolean b = rdOrderAppService.addOrderApps(applyNums.get(i), orderApps, userId, date);
                    Assert.isTrue(!b, "新增自建系统时失败");
                } else {
                    // 如果不是接口数据，则没有自建系统
                    RdResourceApplicationDetail order = new RdResourceApplicationDetail()
                            .setId(idList.get(i))
                            .setState(3)
                            .setApplyUserId(ssoService.getUserId(request))
                            .setApplyTime(date)
                            .setModifyTime(date)
                            .setApplyDeptName(raDetail.getApplyDeptName())
                            .setContactName(raDetail.getContactName())
                            .setContactTel(raDetail.getContactTel())
                            .setRemark(raDetail.getRemark())
                            .setEnclosure(raDetail.getEnclosure());
                    boolean update = resAppDetailService.updateById(order);
                    Assert.notTrue(update, "购物车订单提交时出现数据错误,第" + i + "条");
                }
            }
            // 提交申请到流程
            // 获取资源id
            LambdaQueryWrapper<RdResourceApplicationDetail> wrapperResIdList = new LambdaQueryWrapper<>();
            wrapperResIdList.in(RdResourceApplicationDetail::getId, idList)
                    .isNull(RdResourceApplicationDetail::getVersionNum);
            List<RdResourceApplicationDetail> listRd = resAppDetailService.list(wrapperResIdList);

            // 子订单号列表
            List<String> childNumList = listRd.stream().map(RdResourceApplicationDetail::getApplyNumChild).collect(Collectors.toList());
            // 资源id列表
            List<Integer> resIdList = listRd.stream().map(RdResourceApplicationDetail::getResId).collect(Collectors.toList());
            //准备申请人id
            Integer applyUserId = ssoService.getUserId(request);
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (Integer j = 0; j < resIdList.size(); j++) {
                Map<String, Object> map = new HashMap<>();
                map.put("order_item_no", childNumList.get(j));
                map.put("res_id", "[资源目录]-已归集" + resIdList.get(j));
                map.put("user_id", applyUserId);
                listMap.add(map);
            }
            Integer integer = approvalAllApi.lookResId(listMap);
            Assert.notTrue(integer.equals(1), "流程送审时出错");
            return Response.success(childNumList.get(0));
        } catch (Exception e) {
            log.info("提交申请出现异常！");
        }
        return Response.success();
    }

    @ApiOperation(value = "资源申请列表", response = RdResourceApplicationDetail.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "state", value = "当前状态（0未确认 1未提交、2待审批、3已提交至审批中心、4审批中、5已撤回、6审批通过、7已驳回）"),
            @ApiImplicitParam(name = "resType", value = "资源类型（1.接口 2.数据集/页面资源 3.未上线资源）"),
            @ApiImplicitParam(name = "startTime", value = "申请时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "resName", value = "资源名称")
    })
    @GetMapping("/selectApplyBatch")
    public Response selectApplyBatch(HttpServletRequest request, Page page, Integer state, Integer resType, String startTime, String endTime, String resName) throws UnsupportedEncodingException {

        LambdaQueryWrapper<RdResourceApplicationDetail> lqwWrapper = new LambdaQueryWrapper<>();
        Integer userId = ssoService.getUserId(request);
        UserDTO user = userQueryApi.getUser(userId);
        // 没有版本信息
        lqwWrapper.isNull(RdResourceApplicationDetail::getVersionNum);
        // 资源申请人部门id
        lqwWrapper.eq(null != userId, RdResourceApplicationDetail::getDeptId, user.getOwnDeptId());
        // 订单状态不等于1
        lqwWrapper.ne(RdResourceApplicationDetail::getState, 1);
        // 审批状态
        lqwWrapper.eq(null != state, RdResourceApplicationDetail::getState, state);
        // 资源类型
        lqwWrapper.eq(null != resType, RdResourceApplicationDetail::getResType, resType);
        // 申请日期
        if (StringUtil.isNotBlank(startTime)) {
            lqwWrapper.ge(RdResourceApplicationDetail::getApplyTime, DateUtil.getDate(startTime + " 00:00:00",
                    DateUtil.DATETIME_FORMAT));
        }
        if (StringUtil.isNotBlank(endTime)) {
            lqwWrapper.le(RdResourceApplicationDetail::getApplyTime, DateUtil.getDate(endTime + " 23:59:59",
                    DateUtil.DATETIME_FORMAT));
        }
        // 资源名称搜索
        resName = URLDecoder.decode(resName, "UTF-8");
        lqwWrapper.like(StringUtil.isNotBlank(resName) && StringUtil.isNotEmpty(resName),
                RdResourceApplicationDetail::getResName, resName);
        // 已上线
        lqwWrapper.eq(RdResourceApplicationDetail::getResSituation, 1);
        // 倒序输出
        lqwWrapper.orderByDesc(RdResourceApplicationDetail::getId);

        IPage pageResList = resAppDetailService.page(page, lqwWrapper);
        return Response.success(pageResList);
    }

    @ApiOperation("申请单详情")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "applyNumChild", value = "子订单号 ")
    })
    @GetMapping("/selectResApplyDetails")
    public Response selectResApplyDetails(String applyNumChild, HttpServletRequest request) throws BizException {
        // 准备需要的数据
        Integer userId = ssoService.getUserId(request);
        List<Integer> ownDeptIdList = userQueryApi.getUser(userId).getOwnDeptIdList();
        List<Integer> roleIdList = userQueryApi.getUser(userId).getRoleIdList();

        HashMap<Object, Object> param = new HashMap<>(16);
        // 节点信息查询
        List<TpApproveFlow> tpApproveFlows = approvalAllApi.selectApprovalFlowByResId(applyNumChild);
        param.put("flowParam", tpApproveFlows);
        // 实施工单详情
        RdImplementationOrder oneOrder = rdImplementationOrderService.getOne(Wrappers.<RdImplementationOrder>lambdaQuery()
                .eq(RdImplementationOrder::getApplyNum, applyNumChild));
        if (oneOrder != null && oneOrder.getImplementationState() == 0) {
            param.put("oneOrderParam", oneOrder);
        } else if (oneOrder != null && (oneOrder.getImplementationState() == 1 || oneOrder.getImplementationState() == 2 || oneOrder.getImplementationState() == 3 || oneOrder.getImplementationState() == 4)) {
            if (oneOrder.getFinishUserid() != null) {
                oneOrder.setFinishDeptName(userQueryApi.getUser(oneOrder.getFinishUserid()).getOwnDeptName());
            }
            param.put("oneOrderParam", oneOrder);
        }
        // 订单基础信息查询
        LambdaQueryWrapper<RdResourceApplicationDetail> findSelfSysWrapper = new LambdaQueryWrapper<>();
        findSelfSysWrapper.eq(StringUtil.isNotBlank(applyNumChild), RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                .isNull(RdResourceApplicationDetail::getVersionNum);
        RdResourceApplicationDetail rdResourceApplicationDetail = resAppDetailService.getOne(findSelfSysWrapper);
        // 拿到该订单我的审批节点数据
        TpApproveFlow tpApproveFlow = approvalAllApi.selectApprovalFlowResultByResId(applyNumChild, ownDeptIdList, roleIdList);
        // 自建系统查询
        List<RdOrderApp> listOrderApp = rdOrderAppService.list(Wrappers.<RdOrderApp>lambdaQuery()
                .eq(RdOrderApp::getApplyNum, applyNumChild).isNull(RdOrderApp::getVersionNum));
        // 排除空指针,并确定该数据含有自建系统
        if (listOrderApp.isEmpty()) {
            log.info("本数据不含有自建系统");
        } else {
            param.put("selfSysParam", listOrderApp);
        }

        // 资源信息查询
        Integer resId = null;
        if (rdResourceApplicationDetail != null) {
            resId = rdResourceApplicationDetail.getResId();
        }
        LambdaQueryWrapper<RdResourceDir> selectDir = new LambdaQueryWrapper<>();
        selectDir.eq(resId != null, RdResourceDir::getId, resId);
        List<RdResourceDir> listDir = rdResourceDirService.list(selectDir);
        if (!listDir.isEmpty()) {
            for (RdResourceDir rdResourceDir : listDir) {
                Assert.isNull(rdResourceDir, "无法获取资源信息");
                Integer resType = rdResourceDir.getResType();
                Assert.isNull(resType, "无法获取资源类型");
                if (resType == 1) {
                    RdResDetailsApi one = rdResDetailsApiService.getOne(new LambdaQueryWrapper<RdResDetailsApi>().eq(RdResDetailsApi::getResDirId, resId));
                    if (one != null) {
                        rdResourceDir.setServiceAddress(one.getApiAddress());
                    }
                }
            }
        }
        RdResourceDirData rdResourceDirData = null;
        List<RdResDataItem> rdResDataItemList = new ArrayList<>();
        RdDbDict rdDbDict = null;
        // 如果是交换类资源，查看申请单信息
        if (rdResourceApplicationDetail != null && rdResourceApplicationDetail.getResType() == 3) {
            rdResourceDirData = rdResourceDirDataService.getOne(new LambdaQueryWrapper<RdResourceDirData>().eq(resId != null, RdResourceDirData::getResDirId, resId));
            Assert.isNull(rdResourceDirData, "该资源无编目信息");
            rdResDataItemList = rdResDataItemService.list(new LambdaQueryWrapper<RdResDataItem>().eq(RdResDataItem::getOwnResId, resId));
            rdDbDict = rdDbDictService.getById(rdResourceApplicationDetail.getDbId());
        }
        List<RdDbApp> rdDbAppList = dbAppService.list(new LambdaQueryWrapper<RdDbApp>()
                .eq(RdDbApp::getApplyNum, applyNumChild)
                .isNull(RdDbApp::getVersionNum));
        // 获取所有数据源信息
        List<RdDbDict> dbDicts = rdDbDictService.list(Wrappers.<RdDbDict>lambdaQuery().in(RdDbDict::getDeptId, ownDeptIdList));
        // 所有数据源信息
        param.put("dbDictsParam", dbDicts);
        // 数据库信息
        param.put("rdDbDict", rdDbDict);
        // 资源基本信息
        param.put("rdResourceDirData", rdResourceDirData);
        // 资源编目
        param.put("rdResDataItemList", rdResDataItemList);
        // 该资源申请单当前所选字段
        param.put("rdDbAppList", rdDbAppList);
        param.put("dirParam", listDir);

        // 数据源详情
        RdDbDict oneDict = new RdDbDict();
        RdResourceDir oneDir = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId));
        if (oneDir.getResType() == 3) {
            RdResourceApplicationDetail oneDetail = resAppDetailService.getOne(Wrappers.<RdResourceApplicationDetail>lambdaQuery()
                    .eq(RdResourceApplicationDetail::getApplyNumChild, applyNumChild).isNull(RdResourceApplicationDetail::getVersionNum));
            Integer dbId = oneDetail.getDbId();
            Assert.isNull(dbId, "该订单没有数据源信息，可能是数据错误！");
            oneDict = rdDbDictService.getOne(Wrappers.<RdDbDict>lambdaQuery().eq(RdDbDict::getDbId, dbId));
            oneDict.setItemId(oneDetail.getItemId());
        }
        param.put("dictParam", oneDict);

        // 申请信息查询
        String userName;
        if (rdResourceApplicationDetail != null && rdResourceApplicationDetail.getApplyUserId() != null) {
            userName = userQueryApi.getUser(rdResourceApplicationDetail.getApplyUserId()).getName();
            // String deptName = userQueryApi.getDept(rdResourceApplicationDetail.getApplyUserId()).getName();
            // 插入申请人部门名称&申请人名称
            if (tpApproveFlow == null) {
                rdResourceApplicationDetail.setApplyUserName(userName).setApprovalResult(0);
            } else if (tpApproveFlow.getResult() == 1) {
                rdResourceApplicationDetail.setApplyUserName(userName).setApprovalResult(1);
            } else {
                rdResourceApplicationDetail.setApplyUserName(userName).setApprovalResult(2);
            }
        }
        //申请单详情添加附件信息
        if (rdResourceApplicationDetail != null) {
            String enclosureList = rdResourceApplicationDetail.getEnclosure();
            if (!"".equals(enclosureList) && enclosureList != null) {
                String[] enclosures = enclosureList.split(",");
                List<FileObj> fileListInfo = fsApi.getFileListInfo(Arrays.asList(enclosures));
                rdResourceApplicationDetail.setFileInfo(fileListInfo);
            }
        }
        param.put("resDetailParam", rdResourceApplicationDetail);
        return Response.success(param);
    }

    @ApiOperation("取消申请（撤回）")
    @PostMapping("/cancelApply")
    public Response<Boolean> cancelApply(HttpServletRequest request, @RequestBody @ApiParam(name = "applyNumChild", value = "子订单号") Map<String, Object> map) throws BizException {
        String applyNumChild = (String) map.get("applyNumChild");
        Assert.isNull(applyNumChild, "获取订单id失败，请联系管理员");
        Date date = new Date();
        RdResourceApplicationDetail rdResourceApplicationDetail = resAppDetailService.getOne(new LambdaQueryWrapper<RdResourceApplicationDetail>()
                .eq(RdResourceApplicationDetail::getApplyNumChild, applyNumChild));
        RdResForOnline rdResForOnline = rdResForOnlineService.getOne(new LambdaQueryWrapper<RdResForOnline>()
                .eq(RdResForOnline::getApplicationNum, applyNumChild));
        Integer withdrawUserId = ssoService.getUserId(request);
        Boolean cancel;
        if (rdResForOnline != null && rdResourceApplicationDetail == null) {
            LambdaUpdateWrapper<RdResForOnline> cancelApplyWrapper = new LambdaUpdateWrapper<>();
            cancelApplyWrapper.eq(StringUtil.isNotBlank(applyNumChild), RdResForOnline::getApplicationNum, applyNumChild)
                    .isNull(RdResForOnline::getVersionNum)
                    .set(RdResForOnline::getState, 5)
                    .set(RdResForOnline::getModifyUserId, withdrawUserId)
                    .set(RdResForOnline::getModifyTime, date);
            cancel = rdResForOnlineService.update(cancelApplyWrapper);
        } else if (rdResourceApplicationDetail != null && rdResForOnline == null) {
            LambdaUpdateWrapper<RdResourceApplicationDetail> cancelApplyWrapper = new LambdaUpdateWrapper<>();
            cancelApplyWrapper.eq(StringUtil.isNotBlank(applyNumChild), RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                    .isNull(RdResourceApplicationDetail::getVersionNum)
                    .set(RdResourceApplicationDetail::getState, 5)
                    .set(RdResourceApplicationDetail::getModifyUserId, withdrawUserId)
                    .set(RdResourceApplicationDetail::getModifyTime, date);
            cancel = resAppDetailService.update(cancelApplyWrapper);
        } else {
            cancel = false;
        }

        // 撤回approval项目中产生的数据
        Boolean withdraw = approvalAllApi.withdraw(applyNumChild, withdrawUserId, date, 1);
        Assert.notTrue(cancel && withdraw, "撤回时出现错误");
        return Response.success(withdraw);
    }

    @ApiOperation("修改申请内容")
    @PostMapping("/updateApplyDetail")
    public Response<Boolean> updateApplyDetail(HttpServletRequest request,
                                               @RequestBody @ApiParam(name = "RdResourceApplicationDetailService", value = "实体类(一定要放入该订单的主键id)把自建系统数据放到orderApps里!")
                                                       RdResourceApplicationDetail rdResourceApplicationDetail) throws BizException {
        // 准备需要的数据
        Integer userId = ssoService.getUserId(request);
        Date date = new Date();
        Boolean aBoolean = resAppDetailService.updateApplyDetail(rdResourceApplicationDetail, userId, date);
        Assert.notTrue(aBoolean, "修改失败!");
        return Response.success();
    }

    @ApiOperation("我的资源审批列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "result", value = "我的审批状态(1.未审批 2.已审批)--返回数据中有一个approvalResult(1未审批 2已审批),用于隐藏按钮"),
            @ApiImplicitParam(name = "resName", value = "资源名称"),
            @ApiImplicitParam(name = "resPower", value = "共享方式(1.公开 2.受限)"),
            @ApiImplicitParam(name = "updateFrequency", value = "更新频率  实时1、每小时2、每天3、每月4、每季度5、每半年6、每年7、不更新8，不定时9"),
            @ApiImplicitParam(name = "creatTime", value = "开始时间数据"),
            @ApiImplicitParam(name = "endTime", value = "结束时间数据"),
            @ApiImplicitParam(name = "applicationNum", value = "申请单号"),
            @ApiImplicitParam(name = "applicantDept", value = "申请部门")
    })
    @GetMapping("/selectResApplyOnLine")
    public Response selectResApplyOnLine(Page page,
                                         HttpServletRequest req,
                                         Integer result,
                                         String resName,
                                         Integer resPower,
                                         Integer updateFrequency,
                                         String creatTime,
                                         String endTime,
                                         String applicationNum,
                                         Integer applicantDept) throws UnsupportedEncodingException, BizException {
        // 准备数据
        Integer userId = ssoService.getUserId(req);
        Assert.isNull(ssoService.getUserId(req), "用户请登录");
        List<Integer> ownDeptIdList = userQueryApi.getUser(userId).getOwnDeptIdList();
        List<Integer> roleIdList = userQueryApi.getUser(userId).getRoleIdList();
        // 所有订单中，哪些是需要我审批的(生成节点的订单)
        List<String> applyNumList = approvalAllApi.selectMyApprovalTable(ownDeptIdList, roleIdList, result, "[资源目录]-已归集");
        if (applyNumList.isEmpty()) {
            return Response.success(new Page().setSize(page.getSize()).setCurrent(page.getCurrent()));
        }
        // 根据(更新频率,共享方式)条件筛选数据
        LambdaQueryWrapper<RdResourceDir> selectDirs = new LambdaQueryWrapper<>();
        selectDirs.eq(null != updateFrequency, RdResourceDir::getUpdateFrequency, updateFrequency)
                .eq(null != resPower, RdResourceDir::getResPower, resPower);
        List<RdResourceDir> dirs = rdResourceDirService.list(selectDirs);
        if (dirs.isEmpty()) {
            return Response.success(new Page().setSize(page.getSize()).setCurrent(page.getCurrent()));
        }
        // 搜索结果
        List<Integer> resIds = dirs.stream().map(RdResourceDir::getId).collect(Collectors.toList());

        // 根据(资源名称,和时间条件搜索)
        LambdaQueryWrapper<RdResourceApplicationDetail> selectDetails = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(creatTime)) {
            creatTime = java.net.URLDecoder.decode(creatTime, "UTF-8");
            selectDetails.ge(RdResourceApplicationDetail::getApplyTime, DateUtil.getDate(creatTime + " 00:00:00", DateUtil.DATETIME_FORMAT));
        }
        if (StringUtils.isNotBlank(endTime)) {
            endTime = java.net.URLDecoder.decode(endTime, "UTF-8");
            selectDetails.le(RdResourceApplicationDetail::getApplyTime, DateUtil.getDate(endTime + " 23:59:59", DateUtil.DATETIME_FORMAT));
        }
        // 名称搜索
        resName = URLDecoder.decode(resName, "UTF-8");
        selectDetails.like(StringUtil.isNotBlank(resName), RdResourceApplicationDetail::getResName, resName);
        // 符合(更新频率,共享方式)的资源id, 条件融合
        selectDetails.in(!resIds.isEmpty(), RdResourceApplicationDetail::getResId, resIds);
        // 生成过节点的订单
        selectDetails.in(RdResourceApplicationDetail::getApplyNumChild, applyNumList);
        // 已撤回订单隐藏
        selectDetails.ne(RdResourceApplicationDetail::getState, 5);
        // 有版本的隐藏
        selectDetails.isNull(RdResourceApplicationDetail::getVersionNum);
        // 申请单号
        selectDetails.like(StringUtil.isNotBlank(applicationNum), RdResourceApplicationDetail::getApplyNumChild, applicationNum);
        // 申请部门
        selectDetails.eq(null != applicantDept, RdResourceApplicationDetail::getDeptId, applicantDept);
        // 按时间倒序
        selectDetails.orderByDesc(RdResourceApplicationDetail::getApplyTime);
        IPage pageDate = resAppDetailService.page(page, selectDetails);
        List<RdResourceApplicationDetail> detailList = pageDate.getRecords();
        // 融合条件的结果
        List<String> applyList = detailList.stream().map(RdResourceApplicationDetail::getApplyNumChild).collect(Collectors.toList());
        List<Integer> intResids = detailList.stream().map(RdResourceApplicationDetail::getResId).collect(Collectors.toList());
        // 列表里数据的资源信息
        List<RdResourceDir> listDir = rdResourceDirService.list(Wrappers.<RdResourceDir>lambdaQuery().in(RdResourceDir::getId, intResids));
        // 列表里数据的节点数据
        List<TpApproveFlow> tpApproveFlows = approvalAllApi.selectApprovalFlowByNumOrderList(applyList, ownDeptIdList, roleIdList);
        for (int i = 0; i < detailList.size(); i++) {
            for (int j = 0; j < listDir.size(); j++) {
                if (detailList.get(i).getResId().equals(listDir.get(j).getId())) {
                    detailList.get(i).setResPower(listDir.get(j).getResPower())
                            .setUpdateFrequency(listDir.get(j).getUpdateFrequency());
                }
            }
            for (int k = 0; k < tpApproveFlows.size(); k++) {
                if (detailList.get(i).getApplyNumChild().equals(tpApproveFlows.get(k).getApplyId())) {
                    detailList.get(i).setApprovalResult(tpApproveFlows.get(k).getResult());
                }
            }
        }
        return Response.success(pageDate);
    }

    @ApiOperation("流程配置模板接口")
    @PostMapping("/addApprovalConfigOnLine")
    public Response<Boolean> addApprovalConfigOnLine(HttpServletRequest request,
                                                     @RequestBody @ApiParam(name = "deptId & roldId & resId & resPower",
                                                             value = "部门id，角色id，资源id，资源状态（1.公开 2.受限）") Map<String, Object> map) throws Exception {
        // 拒绝重复发布
        Integer resId = (Integer) map.get("resId");
        Integer isRelease = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId)).getIsRelease();
        Assert.isTrue(isRelease == 1, "该资源已发布，请勿重新发布!");
        // 准备需要的数据
        Integer userId = ssoService.getUserId(request);
        Date date = new Date();
        // (0:发布按钮 1：编辑按钮)
        Boolean aBoolean = resAppDetailService.addApprovalConfigDetail(map, date, userId, 0);
        Assert.notTrue(aBoolean, "发布失败!");
        return Response.success();
    }

    @ApiOperation("资源待回收")
    @PostMapping("/retrieveResource")
    public Response<String> retrieveResource(@RequestBody @ApiParam(name = "resId & retrieveReason", value = "资源id，回收理由") Map<String, Object> map) throws BizException {
        Assert.isNull(map.get("resId"), "无法获取资源信息， 请联系管理员");
        Assert.isNull(map.get("retrieveReason"), "请输入回收理由");
        Assert.isNull(map.get("id"), "请输入请求数据id");
        boolean update = rdImplementationOrderService.update(new LambdaUpdateWrapper<RdImplementationOrder>()
                .eq(RdImplementationOrder::getId, map.get("id"))
                .eq(RdImplementationOrder::getOrderType, 1)
                .set(RdImplementationOrder::getImplementationState, 4)
                .set(RdImplementationOrder::getCancelReason, map.get("retrieveReason")));
        return update ? Response.success("申请完成，待实施人员回收") : Response.error("申请失败，请联系管理员");
    }

    @ApiOperation("审批")
    @PostMapping("/updateApplyDetailOnLine")
    public Response<Boolean> updateApplyDetailOnLine(HttpServletRequest request,
                                                     @RequestBody @ApiParam(name = "applyNumChild & resId & result & auditOpinion",
                                                             value = "子订单号，资源id，审核状态 1-未审核 2-通过 3-驳回，审核意见") Map<String, Object> map) throws Exception {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        String applyNumChild = (String) map.get("applyNumChild");
        List<Integer> ownDeptIdList = userQueryApi.getUser(userId).getOwnDeptIdList();
        List<Integer> roleIdList = userQueryApi.getUser(userId).getRoleIdList();
        TpApproveFlow tpApproveFlow = new TpApproveFlow();
        tpApproveFlow.setApplyId(applyNumChild)
                .setResId("[资源目录]-已归集" + map.get("resId"))
                .setResult((Integer) map.get("result"))
                .setAuditOpinion((String) map.get("auditOpinion"))
                .setUserId(userId);
        // 调用审批接口
        approvalAllApi.updateNodeApprovalResults(tpApproveFlow, ownDeptIdList, roleIdList);

        // 审批成功后，驳回产生历史版本
        if ((Integer) map.get("result") == 3) {
            // 查询原数据
            LambdaQueryWrapper<RdResourceApplicationDetail> selectDetail = new LambdaQueryWrapper<>();
            selectDetail.eq(RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                    .isNull(RdResourceApplicationDetail::getVersionNum);
            RdResourceApplicationDetail oneDetail = resAppDetailService.getOne(selectDetail);
            Integer id = oneDetail.getId();
            // 更新原数据
            // 获得最大的版本号
            LambdaQueryWrapper<RdResourceApplicationDetail> selectDetailAll = new LambdaQueryWrapper<>();
            selectDetailAll.eq(RdResourceApplicationDetail::getApplyNumChild, applyNumChild).isNotNull(RdResourceApplicationDetail::getVersionNum);
            List<RdResourceApplicationDetail> datailAll = resAppDetailService.list(selectDetailAll);
            List<Integer> versionList = datailAll.stream().map(RdResourceApplicationDetail::getVersionNum).collect(Collectors.toList());
            Integer versionMax;
            // 检测
            if (versionList.isEmpty()) {
                versionMax = 1;
            } else {
                versionMax = Collections.max(versionList) + 1;
            }
            // 新增一条新的原数据
            boolean saveDetail = resAppDetailService.save(oneDetail.setState(7));
            Assert.isTrue(!saveDetail, "新增原数据失败");

            LambdaUpdateWrapper<RdResourceApplicationDetail> upDetail = new LambdaUpdateWrapper<>();
            upDetail.eq(RdResourceApplicationDetail::getId, id)
                    .set(RdResourceApplicationDetail::getState, 7)
                    .set(RdResourceApplicationDetail::getVersionNum, versionMax);
            boolean updateDetail = resAppDetailService.update(upDetail);

            if (!updateDetail || !saveDetail) {
                log.info("新增版本数据出错");
                return Response.error();
            }
        }
        return Response.success();
    }

    @ApiOperation("历史版本信息查询")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "applyNumChild", value = "子订单号"),
            @ApiImplicitParam(name = "versionNum", value = "版本号")
    })
    @GetMapping("/selectResHistory")
    public Response selectResHistory(String applyNumChild, Integer versionNum) throws BizException {
        LambdaQueryWrapper<RdResourceApplicationDetail> seDetailHistory = new LambdaQueryWrapper<>();
        seDetailHistory.eq(StringUtil.isNotEmpty(applyNumChild), RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                .eq(versionNum != null, RdResourceApplicationDetail::getVersionNum, versionNum);
        RdResourceApplicationDetail oneHistoryDetail = resAppDetailService.getOne(seDetailHistory);
        HashMap<Object, Object> param = new HashMap<>(16);
        LambdaQueryWrapper<RdResourceApplicationDetail> findSelfSysWrapper = new LambdaQueryWrapper<>();
        findSelfSysWrapper.eq(StringUtil.isNotBlank(applyNumChild), RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                .eq(RdResourceApplicationDetail::getVersionNum, oneHistoryDetail.getVersionNum());
        // 历史订单信息
        RdResourceApplicationDetail rdResourceApplicationDetail = resAppDetailService.getOne(findSelfSysWrapper);
        // 资源信息查询
        Integer resId = rdResourceApplicationDetail.getResId();
        LambdaQueryWrapper<RdResourceDir> selectDir = new LambdaQueryWrapper<>();
        selectDir.eq(resId != null, RdResourceDir::getId, resId);
        List<RdResourceDir> listDir = rdResourceDirService.list(selectDir);
        param.put("dirParam", listDir);

        // 自建系统查询
        List<RdOrderApp> listOrderApp = rdOrderAppService.list(Wrappers.<RdOrderApp>lambdaQuery()
                .eq(RdOrderApp::getApplyNum, applyNumChild)
                .eq(versionNum != null, RdOrderApp::getVersionNum, versionNum));
        // 排除空指针，并确定该数据含有自建系统
        if (listOrderApp.isEmpty()) {
            log.info("本数据不含有自建系统!");
        } else {
            param.put("selfSysParam", listOrderApp);
        }

        // 资源信息查询
        List<RdDbApp> list;
        if (versionNum == 1) {
            list = dbAppService.list(Wrappers.<RdDbApp>lambdaQuery().eq(RdDbApp::getApplyNum, applyNumChild)
                    .eq(RdDbApp::getVersionNum, versionNum));
            if (list.isEmpty()) {
                list = dbAppService.list(Wrappers.<RdDbApp>lambdaQuery().eq(RdDbApp::getApplyNum, applyNumChild)
                        .isNull(RdDbApp::getVersionNum));
            }
        } else {
            list = dbAppService.list(Wrappers.<RdDbApp>lambdaQuery().eq(RdDbApp::getApplyNum, applyNumChild)
                    .eq(RdDbApp::getVersionNum, versionNum));
        }
        // 排除空指针，并确定该数据含有自建系统
        if (list.isEmpty()) {
            log.info("数据源信息为空!");
        } else {
            param.put("dbAppsParam", list);
        }

        // 申请信息查询
        String userName = userQueryApi.getUser(rdResourceApplicationDetail.getApplyUserId()).getName();
        // 插入申请人部门名称&申请人名称
        rdResourceApplicationDetail.setApplyUserName(userName);
        String enclosureList = rdResourceApplicationDetail.getEnclosure();
        List<FileObj> fileObjs = new ArrayList<>();
        // 历史记录的附件信息
        if (!"".equals(enclosureList) && enclosureList != null) {
            String[] enclosures = enclosureList.split(",");
            List<FileObj> fileListInfo = fsApi.getFileListInfo(Arrays.asList(enclosures));
            rdResourceApplicationDetail.setFileInfo(fileListInfo);
        }
        RdResourceDirData rdResourceDirData = null;
        List<RdResDataItem> rdResDataItemList = new ArrayList<>();
        RdDbDict rdDbDict = null;
        // 如果是交换类资源，查看申请单信息
        if (rdResourceApplicationDetail.getResType() == 3) {
            rdResDataItemList = rdResDataItemService.list(new LambdaQueryWrapper<RdResDataItem>().eq(resId != null, RdResDataItem::getOwnResId, resId));
            rdDbDict = rdDbDictService.getById(rdResourceApplicationDetail.getDbId());
        }
        // 数据库信息
        param.put("rdDbDict", rdDbDict);
        // 资源基本信息
        param.put("rdResourceDirData", rdResourceDirData);
        // 资源编目
        param.put("rdResDataItemList", rdResDataItemList);

        param.put("resDetailParam", rdResourceApplicationDetail);
        return Response.success(param);
    }
}
